package customtype

import (
	"database/sql/driver"
	"errors"
	"fmt"
	"time"
)

//时间格式化类型
type LocalTimeDay struct {
	time.Time
}

func (t LocalTimeDay) Value() (driver.Value, error) {
	return t.Unix(), nil
}

func (t *LocalTimeDay) Scan(v interface{}) error {
	switch vt := v.(type) {
	case int64:
		*t = LocalTimeDay{time.Unix(vt, 0)}
	default:
		return errors.New("类型处理错误")
	}
	return nil
}

func (t LocalTimeDay) MarshalJSON() ([]byte, error) {
	if t.IsZero() {
		return []byte("\"\""), nil
	}
	tStr := t.Format("2006-01-02") // 设置格式
	// 注意 json 字符串风格要求
	return []byte(fmt.Sprintf("\"%v\"", tStr)), nil
}

func (m *LocalTimeDay) UnmarshalJSON(data []byte) error {
	if string(data) == "null" || string(data) == `""` {
		return nil
	}
	// Fractional seconds are handled implicitly by Parse.
	tt, err := time.Parse(`"`+time.RFC3339+`"`, string(data))
	*m = LocalTimeDay{tt}
	return err
}
